package cn.itsource.service.impl;

import cn.itsource.config.rabbitmq.RabbitmqConfig;
import cn.itsource.doc.CourseDoc;
import cn.itsource.domain.Course;
import cn.itsource.domain.CourseDetail;
import cn.itsource.domain.CourseMarket;
import cn.itsource.dto.CourseDto;
import cn.itsource.dto.SmsDto;
import cn.itsource.exception.MyException;
import cn.itsource.feign.client.CourseFeignClient;
import cn.itsource.mapper.CourseDetailMapper;
import cn.itsource.mapper.CourseMapper;
import cn.itsource.mapper.CourseMarketMapper;
import cn.itsource.query.CourseQuery;
import cn.itsource.result.JSONResult;
import cn.itsource.service.ICourseService;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bobo
 * @since 2022-11-12
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseDetailMapper courseDetailMapper;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Override
    public JSONResult saveCourse(CourseDto dto) {
        Course course = dto.getCourse();
        course.setStatus(0);//课程状态，下线：0 ， 上线：1
        //TODO 权限做完之后，这里需要获取当前登录人的ID进行赋值
        course.setUserId(null);
        course.setUserName(null);
        course.setTenantId(null);
        course.setTenantName(null);
        courseMapper.insert(course);

        CourseDetail courseDetail = dto.getCourseDetail();
        courseDetail.setId(course.getId());
        courseDetailMapper.insert(courseDetail);

        CourseMarket courseMarket = dto.getCourseMarket();
        courseMarket.setId(course.getId());
        courseMarketMapper.insert(courseMarket);

        return JSONResult.success();
    }

    @Override
    public Page<CourseDto> selectMyPage(CourseQuery query) {
        Page<CourseDto> page = new Page<>(query.getPage(), query.getRows());
        List<CourseDto> courseAddDtoList = courseMapper.selectMyPage(page, query.getKeyword());
        return page.setRecords(courseAddDtoList);
    }

    @Autowired
    private CourseFeignClient courseFeignClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //课程上线接口
    @Override
    public JSONResult onLineCourse(CourseQuery query) {
        /**
         * 1、入参校验
          * 2、根据ID集合查询所有课程记录
          * 3、修改状态（未上线改成已上线）
          * 4、课程数据存ES
          * 5、发营销信息
         */

        //1、入参校验
        if(query.getIds() == null){
            throw new MyException("请勾选课程记录");
        }

        //2、根据ID集合查询所有课程记录(数组转List)
        List<Course> courseList = courseMapper.selectBatchIds(Arrays.asList(query.getIds()));

        //3、修改状态（未上线改成已上线）
        List<CourseDoc> docList = new ArrayList<>();
        CourseDoc doc = null;
        for(int i=0; i<courseList.size(); i++){
            Course course = courseList.get(i);
            if(course.getStatus() == 0){
                course.setStatus(1);//课程状态，下线：0 ， 上线：1
                course.setOnlineTime(new Date());
                courseMapper.updateById(course);
                CourseMarket courseMarket = courseMarketMapper.selectById(course.getId());

                doc = new CourseDoc();
                //值的拷贝
                BeanUtils.copyProperties(course, doc);
                BeanUtils.copyProperties(courseMarket, doc);
                docList.add(doc);
            }
        }

        if(docList.size()>0){
            //4、课程数据存ES
            JSONResult jsonResult = courseFeignClient.saveBatchCourse2Es(docList);
            if(!jsonResult.isSuccess()){
                throw new MyException(jsonResult.getMessage());
            }
        }else{
            throw new MyException("没有课程需要上线");
        }

        //5、发营销信息
        //查询需要接收此短信的用户集合
        List<String> phoneList = new ArrayList<>();//假设这里有5000人
        String smsContene = "尊敬的xxxx用户，我们课程有上新，快来体验，前100名，只需要19.9元，链接：http://www.baidu.com";
        //同步变异步：多线程，MQ

        SmsDto dto = new SmsDto();
        dto.setContent(smsContene);
        dto.setPhone(phoneList);

        //发送短信消息
        rabbitTemplate.convertAndSend(
                RabbitmqConfig.EXCHANGE_HRM,
                "course.sms",
                dto, new MyMessage());
        //发送邮件消息
        rabbitTemplate.convertAndSend(
                RabbitmqConfig.EXCHANGE_HRM,
                "course.email",
                smsContene, new MyMessage());
        return JSONResult.success();
    }
}

class MyMessage implements MessagePostProcessor {

    @Override
    public Message postProcessMessage(Message message) throws AmqpException {
        //消息持久化
        message.getMessageProperties().setReceivedDeliveryMode(MessageDeliveryMode.PERSISTENT);
        return message;
    }
}